package com.joney.common.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.joney.common.enums.GlobalErrorCodeEnum;
import com.joney.common.enums.IEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

/**
 * @author wangxianchen
 * @create 2018-01-17
 * @desc
 */
@Getter
@Setter
@ToString
@JsonSerialize(include =  JsonSerialize.Inclusion.NON_NULL)
public class Result<T> implements Serializable {

    private int code;

    private String msg;

    private T data;

    public Result(){
        this.code = GlobalErrorCodeEnum.SUCCESS.code();
        this.msg = GlobalErrorCodeEnum.SUCCESS.msg();
        this.data = null;
    }

    public Result(IEnum iEnum){
        this.code = iEnum.code();
        this.msg = iEnum.msg();
    }

    @JSONField(serialize=false)
    @JsonIgnore
    public void fail(IEnum errorCodeEnum){
        this.code = errorCodeEnum.code();
        this.msg = errorCodeEnum.msg();
    }
    @JSONField(serialize=false)
    @JsonIgnore
    public static Result fail(){
       return new Result(GlobalErrorCodeEnum.FAIL);
    }


    /**
     * @desc 带消息的默认失败返回对象
     * @author wangxianchen
     * @create 2018-04-21
     * @param msg
     * @return
     */
    @JSONField(serialize=false)
    @JsonIgnore
    public static Result fail(String msg){
        Result ret = new Result(GlobalErrorCodeEnum.FAIL);
        ret.setMsg(msg);
        return ret;
    }

    /**
     * @desc 默认成功的返回对象
     * @author wangxianchen
     * @create 2018-03-26
     * @return
     */
    @JSONField(serialize=false)
    @JsonIgnore
    public static Result success(){
        return new Result();
    }

    /**
     * @desc 默认成功的返回指定对象
     * @author wangxianchen
     * @create 2018-04-26
     * @param body
     * @return
     */
    @JSONField(serialize=false)
    @JsonIgnore
    public static<T> Result<T> success(T body){
        Result ret = new Result();
        ret.setData(body);
        return ret;
    }
}
